package com.learning.spring.optimize.property.editor;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * ClassName: PropertyEditor
 * Description: 属性编辑器
 * Date: 2018/8/7 15:52 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class SpringPropertyEditor {


    /**
     * Spring 的属性编辑器，负责将配置文件中的文本配置值转换为Bean 的属性对应值。Spring 为常见的属性类型提供了默认的属性编辑器。
     * BeanWrapperImpl 类扩展了 PropertyEditorRegistrySupport 类。PropertyEditorRegistrySupport 类为常见属性类型提供默认的属性编辑器
     * <p>
     * PropertyEditorRegistrySupport 中常见类型，分为三类
     * <p>
     * 两个属性
     * private Map<Class<?>, PropertyEditor> defaultEditors; 保存默认属性类型的编辑器，key-属性类型、value-属性编辑器实例
     * private Map<Class<?>, PropertyEditor> customEditors; 保存用户自定义的属性编辑器
     */
    static void test2() {

    }


    /**
     * 自定义属性编辑器：
     * 1、继承 java.beans.PropertyEditorSupport，如CustomDateEditor、CustomNumberEditor等
     * 2、注册自定义属性编辑器：
     */
    static void test3() {

    }

    @Setter
    @Getter
    class Person {
        private String name;
        private int age;
        private Address address;
    }

    @Setter
    @Getter
    class Address {
        private String area;
        private String desc;
    }


    /**
     * 自定义 Address 的属性编辑器
     */
    class AddressEditor extends PropertyEditorSupport {

        private static final String FLAG = ",";

        @Override
        public void setAsText(String text) throws IllegalArgumentException {

            if (StringUtils.isEmpty(text) || !text.contains(FLAG)) {
                throw new IllegalArgumentException("设置的字符串格式不正确");
            }

            String[] split = text.split(",");
            Address address = new Address();
            address.setArea(split[0]);
            address.setDesc(split[1]);
            // 调用父类方法设置转换后的属性对象
            super.setValue(address);
        }
    }


    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {

        binder.registerCustomEditor(Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-mm-dd"), true));
    }


}
